package com.iexbuy.ihg.ui.fragment;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.ShopsAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.AdObject;
import com.iexbuy.ihg.entity.BusinessType;
import com.iexbuy.ihg.entity.LingQianMyProfile;
import com.iexbuy.ihg.entity.LingQianSuccessObject;
import com.iexbuy.ihg.entity.LingQianSummaryObject;
import com.iexbuy.ihg.entity.Shop;
import com.iexbuy.ihg.entity.YunItemListObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.ui.activity.MainTabActivity;
import com.iexbuy.ihg.ui.view.FixGridLayout;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HomeMianDanFragment extends BaseFragment {
	
	private static HomeMianDanFragment homeFragmentInstent;

	@ViewInject(R.id.pullToRefreshLayout)
	private PullToRefreshLayout pullToRefreshLayout;

	@ViewInject(R.id.goinBalance)
	private TextView goinBalance;
	@ViewInject(R.id.totalCash)
	private TextView totalCash;
	@ViewInject(R.id.attenceNoGrid)
	private GridView attenceNoGrid;
	@ViewInject(R.id.currenSequence)
	private TextView currenSequence;
	@ViewInject(R.id.cashInNoLayout)
	private LinearLayout cashInNoLayout;
	@ViewInject(R.id.dayBalance)
	private TextView dayBalance;

	private View rootView;

	private List<AdObject> adObjects = new ArrayList<AdObject>();
	private List<View> adItemViews = new ArrayList<View>();

	private List<Shop> shops = new ArrayList<Shop>();
	private int pageNo = 0;
	private ShopsAdapter shopsAdapter;

	//云购
	private List<YunItemListObject> yunItemListObjects = new ArrayList<YunItemListObject>();

	//热门分类
	private List<BusinessType> businessTypes = new ArrayList<BusinessType>();
	private List<View> businessTypePageViews = new ArrayList<View>();

	private LingQianMyProfile profile;
	private LingQianSummaryObject summaryObject;
	private static boolean isFirst =false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_miandan, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.title_mian_dan));
		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setLeftButtonVisibility(View.GONE);
//		mBaseActivity.setHomeLeftButton(new View.OnClickListener() {
//			@Override
//			public void onClick(View view) {
//				MainTabActivity.getInstance().setCurrentTab(0);
//			}
//		});
		mBaseActivity.setSlideRightBackEnable(false);
		mBaseActivity.setRightButton("规则", new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				CommUtil.openSingleFragmentActivity(mBaseActivity, MianDanRuleFragment.class);
			}
		});

		pullToRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				refreshDate();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				pullToRefreshLayout.refreshFinish(PullToRefreshLayout.DONE);
			}
		});
		pullToRefreshLayout.autoRefresh();
	}

	//刷新整个页面数据
	private void refreshDate() {
		initListDate();
		getLingQianSummary();
	}

	@Override
	public void onResume() {
		super.onResume();
		if (isFirst){
			refreshDate();
		}
		isFirst=true;
	}


	/**
	 * 获取个人信息
	 */
	private void initListDate() {
		if (StringUtil.isEmpty(App.sPreferences.getUserId())) {
			LoginFragment.setIsLoginForbusiness(true);
			CommUtil.openSingleFragmentActivity(mBaseActivity, LoginFragment.class);
		}
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userId", App.sPreferences.getUserId());
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_MY_MIAN_DAN_PRODILE, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						pullToRefreshLayout.refreshFinish(PullToRefreshLayout.REFRESHING);
					}

					@Override
					public void onCancelled() {
						pullToRefreshLayout.refreshFinish(PullToRefreshLayout.DONE);
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
						profile = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), LingQianMyProfile.class);
						initProfileView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	private void initProfileView() {
		if (profile == null)  {
			return;
		}

		goinBalance.setText(profile.getAvailableLingQianCoin());

		totalCash.setText(profile.getReceivedMoney());
		dayBalance.setText(Html.fromHtml("单日剩余次数 <b>" + profile.getRemainQueueNumber() + "</b>"));

		if (profile.getLastestPosition() != null) {
			attenceNoGrid.setAdapter(new BaseAdapter() {
				@Override
				public int getCount() {
					return profile.getLastestPosition().size();
				}
				@Override
				public Object getItem(int i) {
					return profile.getLastestPosition().get(i);
				}
				@Override
				public long getItemId(int i) {
					return 0;
				}
				@Override
				public View getView(int i, View view, ViewGroup viewGroup) {
					if (view == null) {
						view = new TextView(mBaseActivity);
					}
					((TextView)view).setTextColor(getResources().getColor(R.color.main_important_text_color));
					((TextView)view).setText(profile.getLastestPosition().get(i).getPosition());
					return view;
				}
			});
		}

		if (profile.getLuckPositions() != null) {
			TextView tv = null;
			cashInNoLayout.removeAllViews();
			if (profile.getLuckPositions().size() > 0) {
				for (LingQianMyProfile.Position postion : profile.getLuckPositions()) {
					tv = new TextView(mBaseActivity);
					tv.setText(postion.getPosition());
					tv.setBackgroundColor(getResources().getColor(R.color.main_important_text_color));
					tv.setTextColor(getResources().getColor(R.color.white));
					cashInNoLayout.addView(tv);
				}
			} else {
				tv = new TextView(mBaseActivity);
				tv.setText("亲，暂无兑现号码");
				tv.setTextColor(getResources().getColor(R.color.main_important_text_color));
				cashInNoLayout.addView(tv);
			}

		}
	}

	/**
	 * 获取领钱信息
	 */
	private void getLingQianSummary() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_LING_QIANG_SUMMARY, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						summaryObject = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), LingQianSummaryObject.class);
						initSummryView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	private void initSummryView() {
		currenSequence.setText(summaryObject.getAttandUserNumber());
	}

	@OnClick(R.id.checkYunguoRecordBtn)
	public void oncheckYunguoRecordBtnClick(View view) {
		if (Integer.valueOf(profile.getAvailableLingQianCoin()) < 100) {
			ToastUtils.toast(mBaseActivity, "金币不够，消费支付可增加金币喔～～");
			return;
		} else {
			CommUtil.showConfirmAlert(mBaseActivity, "您将花费100金币参与排队免单100元", new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					HashMap<String, String> paramMap = new HashMap<String, String>();
					paramMap.put("userId", App.sPreferences.getUserId());
					ServiceHelper.send(mBaseActivity, ServiceHelper.SUBMIT_LING_QIANG, paramMap,
						new RequestCallBack<String>() {
							@Override
							public void onStart() {
							}

							@Override
							public void onCancelled() {
							}

							@Override
							public void onSuccess(ResponseInfo<String> responseInfo) {
								LingQianSuccessObject response = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), LingQianSuccessObject.class);
								MianDanResultFragment.setLingQianSuccessObject(response);
								CommUtil.openSingleFragmentActivity(mBaseActivity, MianDanResultFragment.class);
							}

							@Override
							public void onFailure(HttpException error, String msg) {
								ToastUtils.toast(mBaseActivity, msg);
							}
						});
				}
			}, null);
		}
	}

	/**
	 * 兑现记录详情页面跳转
	 * @param arg0
	 */
	@OnClick(R.id.totalCashBtn)
	public void totalCashBtnClick(View arg0) {
		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeMianDanRecordsFragment.class);

	}
	/**
	 * 我的排队号码
	 * @param arg0
	 */
	@OnClick(R.id.queueRecordBtn)
	public void queueRecordBtnClick(View arg0) {
		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeMianDanQueueRecordsFragment.class);

	}
	/**
	 * 当前排号人次
	 * @param arg0
	 */
	@OnClick(R.id.currentRecordBtn)
	public void currentRecordBtnClick(View arg0) {
		WeDeMianDanCashNumberFragment.setLingQianSummaryObject(summaryObject);
		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeMianDanCashNumberFragment.class);

	}
	/**
	 * 全站已兑换记录详情页面跳转
	 * @param arg0
	 */
	@OnClick(R.id.cashInNoLayout)
	public void queueCountBtnClick(View arg0) {
		WeDeMianDanQueueCashFragment.setLingQianSummaryObject(summaryObject);

		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeMianDanQueueCashFragment.class);


	}
	/**
	 * @return the homeFragmentInstent
	 */
	public static HomeMianDanFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}


}
